// src/components/scholarDashboard/mainContent/ColumnSelector.tsx

import type { FC } from 'react';
import { useCallback, useMemo } from 'react';
import { FiLock, FiCheckSquare, FiXSquare, FiX } from 'react-icons/fi';
import { useState } from 'react';

interface HeaderOption {
  key: string;
  label: string;
}

interface ColumnSelectorProps {
  allHeaders: HeaderOption[];
  selectedHeaders: string[];
  updateSelectedHeaders: (keys: string[]) => void;
}

const ColumnSelector: FC<ColumnSelectorProps> = ({
  allHeaders,
  selectedHeaders,
  updateSelectedHeaders,
}) => {
  const [showOptions, setShowOptions] = useState(false);

  const dependencyMap = useMemo((): Record<string, string[]> => ({
    full_name: ['preferred_name'],
    default_email: ['alternate_email'],
  }), []);

  const parentMap = useMemo(() => {
    const map: Record<string, string> = {};
    Object.entries(dependencyMap).forEach(([parent, children]) => {
      children.forEach((child) => {
        map[child] = parent;
      });
    });
    return map;
  }, [dependencyMap]);

  const toggleHeader = useCallback(
    (key: string) => {
      const isSelected = selectedHeaders.includes(key);
      let updated = [...selectedHeaders];
      const children = dependencyMap[key] || [];
      if (isSelected) {
        updated = updated.filter((h) => h !== key && !children.includes(h));
      } else {
        updated.push(key);
        children.forEach((child: string) => {
          if (!updated.includes(child)) updated.push(child);
        });
      }
      updateSelectedHeaders(updated);
    },
    [selectedHeaders, updateSelectedHeaders, dependencyMap]
  );

  const groupedFields = [
    {
      group: "Basic Info",
      fields: [
        "student_number", "program", "year", "full_name", "preferred_name", "default_email", "alternate_email", "gender", "date_of_birth", "university_status", "start_date", "end_date", "scholar_type"
      ]
    },
    {
      group: "School Info",
      fields: [
        "school_code", "school_name", "gateway_school", "indigenous_student"
      ]
    },
    {
      group: "Health & Dietary",
      fields: [
        "dietary_preference", "dietary_allergies", "dietary_religious", "medical_allergies"
      ]
    },
    {
      group: "ITE Placement Info",
      fields: [
        "ite_number", "sponsor_name", "department", "supervisors", "ite_start", "ite_end", "ite_details_input_date", "ite_input_in_time", "latest_start_date", "expected_finish_date", "start_date_met", "end_date_met", "it_change_approved"
      ]
    },
    {
      group: "PD Agreement",
      fields: [
        "pd_agreement_submission_date", "placement_mid_point"
      ]
    },
    {
      group: "MPC",
      fields: [
        "mpc_call_date", "mpc_call_on_time", "mpc_document_due_date", "mpc_submitted_date", "mpc_submitted_on_time"
      ]
    },
    {
      group: "Presentation",
      fields: [
        "end_of_it_presentation_date", "end_of_it_input_date", "it_presentation_completed_ontime", "unsw_attendee_on_presentation"
      ]
    },
    {
      group: "Evaluation & Grades",
      fields: [
        "sponsor_evaluation_sent_to_sponsor_date", "sent_before_end_of_placement", "sponsor_completed_date", "placement_completed_date", "placement_grade", "placement_performance", "grade_updated", "grade_updated_date", "sponsor_evaluation_completed_on_time", "scholar_comment"
      ]
    }
  ];

  const [expandedGroup, setExpandedGroup] = useState<string | null>(null);

  return (
    <div className="w-full px-4 sm:px-6 py-3 mb-2 font-poppins">
      {/* Always show a single button per row to open column selector */}
      <div className="flex justify-center items-center">
        <button
          onClick={() => setShowOptions((v) => !v)}
          className="w-full max-w-lg flex items-center justify-center gap-3 px-4 py-3 text-base rounded-xl border border-blue-400 text-blue-700 dark:text-cyan-300 bg-white dark:bg-slate-800 shadow-md hover:bg-blue-50 dark:hover:bg-slate-700 hover:shadow-lg transition-all duration-200 font-medium focus:outline-none focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 focus:ring-offset-2"
          style={{ letterSpacing: '0.01em' }}
        >
          {showOptions ? <FiX className="text-blue-500 dark:text-cyan-300 text-lg" /> : <FiCheckSquare className="text-blue-500 dark:text-cyan-300 text-lg" />}
          {showOptions ? 'Close Column Selector' : 'Choose Columns'}
        </button>
      </div>
      {/* Popup selection for all screens */}
      <div className="flex flex-col items-center">
        {showOptions && (
          <div className="relative animate-fade-in-up mt-3 p-8 rounded-2xl border border-gray-200 dark:border-slate-700 shadow-xl bg-white dark:bg-slate-800 z-30 flex flex-col gap-6 w-full max-w-7xl transition-all duration-300">
            {/* Close button */}
            <button
              onClick={() => setShowOptions(false)}
              className="absolute top-5 right-5 text-gray-400 dark:text-gray-500 hover:text-blue-500 dark:hover:text-cyan-300 text-lg focus:outline-none focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 rounded-full p-1 transition-all duration-200"
              aria-label="Close column selector"
            >
              <FiX />
            </button>

            {/* Select/Clear all row */}
            <div className="flex gap-4 justify-center">
              <button
                onClick={() => updateSelectedHeaders(allHeaders.map((h) => h.key))}
                className="flex items-center gap-2 px-5 py-2.5 text-sm rounded-xl border border-blue-400 dark:border-cyan-700 text-blue-700 dark:text-cyan-300 bg-blue-50 dark:bg-slate-700 hover:bg-blue-100 dark:hover:bg-cyan-800 active:bg-blue-200 dark:active:bg-cyan-900 shadow-sm font-medium focus:outline-none focus:ring-2 focus:ring-blue-300 dark:focus:ring-cyan-700 transition-all duration-200"
              >
                <FiCheckSquare className="text-blue-500 dark:text-cyan-300" />
                Select All
              </button>
              <button
                onClick={() => updateSelectedHeaders([])}
                className="flex items-center gap-2 px-5 py-2.5 text-sm rounded-xl border border-red-300 text-red-600 dark:text-red-300 bg-red-50 dark:bg-slate-700 hover:bg-red-100 dark:hover:bg-red-800 active:bg-red-200 dark:active:bg-red-900 shadow-sm font-medium focus:outline-none focus:ring-2 focus:ring-red-200 dark:focus:ring-red-700 transition-all duration-200"
              >
                <FiXSquare className="text-red-400 dark:text-red-300" />
                Clear All
              </button>
            </div>

            <div className="border-t border-gray-100 dark:border-slate-700 my-2" />

            {/* Two-column layout for field groups */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 w-full">
              {groupedFields.map(({ group, fields }) => (
                <div key={group} className="w-full">
                  <button
                    className={`w-full flex items-center justify-between px-4 py-3 rounded-xl font-bold text-sm border border-blue-200 dark:border-cyan-700 bg-blue-50 dark:bg-slate-700 hover:bg-blue-100 dark:hover:bg-cyan-800 transition-all duration-200 mb-3 focus:outline-none focus:ring-2 focus:ring-blue-300 dark:focus:ring-cyan-700`}
                    onClick={() => setExpandedGroup(expandedGroup === group ? null : group)}
                    aria-expanded={expandedGroup === group}
                  >
                    <span className="text-blue-700 dark:text-cyan-300">{group}</span>
                    <span className="ml-2 text-blue-500 dark:text-cyan-300 text-lg">{expandedGroup === group ? '▲' : '▼'}</span>
                  </button>
                  {expandedGroup === group && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-3">
                      {fields.map(key => {
                        const header = allHeaders.find(h => h.key === key);
                        if (!header) return null;
                        const label = header.label;
                        const parent = parentMap[key];
                        const isSelected = selectedHeaders.includes(key);
                        const isDisabled = parent ? !selectedHeaders.includes(parent) : false;
                        return (
                          <button
                            key={key}
                            onClick={() => !isDisabled && toggleHeader(key)}
                            disabled={isDisabled}
                            className={`flex items-center gap-2 px-3 py-2 text-sm rounded-xl font-medium shadow-sm focus:outline-none focus:ring-2 transition-all duration-200 min-h-[40px] w-full
                              ${isDisabled
                                ? 'bg-gray-100 dark:bg-slate-700 text-gray-400 border border-gray-200 dark:border-slate-700 cursor-not-allowed'
                                : isSelected
                                  ? 'bg-blue-600 dark:bg-cyan-700 text-white border border-blue-600 dark:border-cyan-700 hover:bg-blue-700 dark:hover:bg-cyan-800 focus:ring-blue-300 dark:focus:ring-cyan-700 shadow-md'
                                  : 'bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-100 border border-gray-300 dark:border-slate-700 hover:bg-blue-50 dark:hover:bg-slate-700 hover:border-blue-300 dark:hover:border-cyan-700 focus:ring-blue-200 dark:focus:ring-cyan-700'}
                            `}
                            tabIndex={isDisabled ? -1 : 0}
                            aria-disabled={isDisabled}
                            aria-pressed={isSelected}
                            style={{ letterSpacing: '0.01em' }}
                          >
                            {isDisabled && <FiLock className="text-gray-400 flex-shrink-0" title="Select parent column first" />}
                            <span className="text-xs sm:text-sm break-words leading-tight text-left flex-1">
                              {label}
                            </span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ColumnSelector;